import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { logout, login } from '@/scripts/auth'
import global from '@/scripts/global'
// import { getTokenInfo,getTokenDetail } from "./util";
import router from './router';
// let token = null;
// let isFetchingToken = false;

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 600 // request timeout
})

// request interceptor
service.interceptors.request.use(
  async config => {
    // if(!sessionStorage.getItem('access_token')){
    //   let item = await getTokenInfo();
    //   if (!item.token && !isFetchingToken && item.yzhExchangeToken) {
    //     isFetchingToken = true;
    //     token = await getTokenDetail(item.yzhExchangeToken);   
    //     isFetchingToken = false;
    //     sessionStorage.setItem('access_token',token);
    //   }
    //   if(item&&item.token){
    //     token = item.token;
    //     sessionStorage.setItem('access_token',token);
    //   }    
    // }    
    let accessToken = sessionStorage.getItem('access_token');
    if(accessToken){
      config.url = config.url
        .concat(config.url.indexOf("?") >= 0 ? (accessToken ? "&" : "") : "?")
        .concat(accessToken ? `token=${accessToken}` : "");     
    }    
    return config;
  },
  error => {  
    return Promise.reject(error)
  }
)

var currentMessage
service.interceptors.response.use(
  response => {
    if (response.config.url.indexOf('user/info') !== -1 && response.data.code === 402) {
      logout()
    }
    return new Promise((reslove, reject) => {
      const res = response.data
      if (res.code !== 200) {
        var duration = 5
        // if(res.data[0].code){
        // console.log(res.data[0].code);
        // }
        if (res.code === 402) {
          duration = 1
          if(global.user.info.username){
            ElMessageBox.prompt(`当前账号：${global.user.info.username}凭证已过期，请输入密码重新登录`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '退出',
              inputType: 'password',
              closeOnClickModal: false,
              beforeClose: (action, instance, done) => {
                if (action === 'confirm') {
                  login({
                    username: global.user.info.username,
                    password: instance.inputValue
                  }).then((res) => {
                    if (res) {
                      done()
                      service(response.config).then(ret => reslove(ret))
                    }
                  })
                } else if (action === 'cancel') {
                  logout()
                } else {
                  done()
                }
              }
            })
          }
        }
        if (res.code !== 402) {
          if(currentMessage){
            currentMessage.close()
          }
          if(res.code == 403 && import.meta.env.MODE == 'demo'){
            res.message = '演示模式，不允许操作！'
          }
          currentMessage = ElMessage({
            message: res.message || 'Error',
            type: 'error',
            duration: duration * 1000,
            showClose: true
          })
          reject(res)
        }
      } else {
        reslove(res)
        if(res.code === 200 && res.data.code === 401){
          sessionStorage.removeItem('access_token');
          router.push({ 
            path: '/error',
            query:{message:res.data.message}
          });
        }
      }
    })
  },
  error => {
    if(currentMessage){
      currentMessage.close()
    }
    currentMessage = ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
